package com.sec.android.app.myfiles.module.local.recent;

import android.content.Intent;
import android.content.res.Configuration;
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.util.TypedValue;
import android.view.View;
import android.widget.TextView;

import com.sec.android.app.myfiles.R;
import com.sec.android.app.myfiles.facade.MyFilesFacade;
import com.sec.android.app.myfiles.fragment.filelist.FileListFragment;
import com.sec.android.app.myfiles.info.AppConstants;
import com.sec.android.app.myfiles.listener.ListenerMgr;
import com.sec.android.app.myfiles.listener.RecentInsertedFromOutOfMyFiles;
import com.sec.android.app.myfiles.module.abstraction.FileRecord;
import com.sec.android.app.myfiles.navigation.NavigationInfo;
import com.sec.android.app.myfiles.navigation.NavigationManager;
import com.sec.android.app.myfiles.operation.FileOperationArgs;
import com.sec.android.app.myfiles.operation.FileOperator;
import com.sec.android.app.myfiles.operation.ProgressListener;
import com.sec.android.app.myfiles.provider.PrivateMyFilesProvider;
import com.sec.android.app.myfiles.util.PreferenceUtils;
import com.sec.android.app.myfiles.util.SmartTipUtils;
import com.sec.android.app.myfiles.util.UiUtils;

import java.util.ArrayList;

public class FullRecentListFragment extends FileListFragment implements ProgressListener {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mListenerMgr.addListener(new RecentInsertedFromOutOfMyFiles(mContext, mUpdateRunnable,
                ListenerMgr.LifeCycle.RESUME, ListenerMgr.LifeCycle.PAUSE));
//        SamsungAnalyticsLog.setScreenInfo(SamsungAnalyticsLog.ScreenPath.RECENT_FILES);   //TODO : HJ SA
    }

    @Override
    public void onResume() {
        super.onResume();
        if (PreferenceUtils.getShowRecentFiles(mContext)) {
            int invalidRecentCount;
            Cursor cursor = mAdapter.getCursor();
            if (cursor != null) {
                invalidRecentCount = removeInvalidRecent(cursor);
                if (cursor.getCount() > 0 && invalidRecentCount == 0) {
                    FileRecord record = UiUtils.getRecentRecord();
                    if (record != null) {
                        PrivateMyFilesProvider.refreshDb(mContext, record);
                        reload();
                    }
                }
            }

            if (SmartTipUtils.canShowSmartTip(mContext)) {
                Intent intent = new Intent(AppConstants.CHECK_SMART_TIP);
                LocalBroadcastManager.getInstance(mContext).sendBroadcast(intent);
            }
        } else {
            MyFilesFacade.goHome(mProcessId, null, mContext);
        }
    }

    @Override
    public void onLoadFinished() {
        super.onLoadFinished();

        if (mAdapter != null) {
            Cursor data = mAdapter.getCursor();
            if (removeInvalidRecent(data) > 0) {
                data.close();
                mAdapter.changeCursor(null);
            } else {
                if (data != null && data.getCount() == 0) {
                    finishActionMode();
                } else {
                    mAdapter.changeCursor(data);
                }
            }
            updateActionBarMenu();
        }
        enableClearHistoryButton();
    }

    private int removeInvalidRecent(Cursor data) {
        int ret = 0;
        if (data != null && !data.isClosed()) {
            if (data.moveToFirst()) {
                ArrayList<FileRecord> records = new ArrayList<>();
                FileRecord record;
                do {
                    record = mAdapter.getFileRecord(data);
                    if (record != null && !record.exists(mContext)) {
                        records.add(record);
                    }
                } while (data.moveToNext());
                ret = records.size();
                removeRecent(records);
            }
        }

        if (ret != 0) {
            finishActionMode();
        }
        return ret;
    }

    private void removeRecent(ArrayList<FileRecord> recordList) {
        if (recordList != null && !recordList.isEmpty()) {
            FileOperator operator = FileOperator.getInstance(getProcessId(), mContext, getFragmentManager(), null);
            FileOperationArgs args = new FileOperationArgs();
            args.mProcessId = getProcessId();
            args.mSrcList = recordList;
            operator.setOperationArgs(FileOperator.Operation.DELETE, args);
            operator.registerProgressListener(this, null);
            operator.execute();
        }
    }

    @Override
    public void onProgressChanged(String fileName, int progress, int total) {

    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        refreshClearHistoryButton();
    }

    @Override
    public void onFinished(boolean bRet, String msg, Bundle extras) {
        reload();
    }

    private Runnable mUpdateRunnable = new Runnable() {
        @Override
        public void run() {
            reload();
        }
    };

    @Override
    protected void setClearHistoryButton() {
        mClearHistoryButton = getActivity().findViewById(R.id.clear_history_button);
        if (mClearHistoryButton != null) {
            NavigationInfo curNaviInfo = NavigationManager.getInstance(getProcessId()).getCurInfo();
            if (curNaviInfo != null && curNaviInfo.getStorageType() == FileRecord.StorageType.Recent) {
                if (isSelectActionMode()) {
                    mClearHistoryButton.setVisibility(View.GONE);
                    mClearHistoryButton.setOnClickListener(null);
                } else {
                    mClearHistoryButton.setVisibility(View.VISIBLE);
                    mClearHistoryButton.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            MyFilesFacade.clearRecent(getProcessId(), mContext);
                        }
                    });
                }
            } else {
                mClearHistoryButton.setVisibility(View.GONE);
                mClearHistoryButton.setOnClickListener(null);
            }
        }
    }

    private void enableClearHistoryButton() {
        if (mClearHistoryButton != null) {
            boolean isEnabled = getTotalFileCount() > 0;
            mClearHistoryButton.setEnabled(isEnabled);
            mClearHistoryButton.setFocusable(isEnabled);
        }
    }

    private void refreshClearHistoryButton() {
        if (mClearHistoryButton != null) {
            ((TextView) mClearHistoryButton).setTextSize(TypedValue.COMPLEX_UNIT_PX,
                    mContext.getResources().getDimensionPixelSize(R.dimen.navigation_view_item_text_size));
        }
    }

    @Override
    public void setActionMode(ActionModeType actionMode) {
        super.setActionMode(actionMode);
        setClearHistoryButton();
    }
}
